//
//  JCPlanIntelligentController.m
//  JiFengDaRen
//
//  Created by shouhan on 2018/5/18.
//  Copyright © 2018年 陈永发. All rights reserved.
//

#import "JCPlanIntelligentController.h"
#import "JCPlanTableViewCell.h"
#import "JCBillPreviewController.h"
#import "JCAddressPickerView.h"
#import "JCPickerView.h"
#import "JXTAlertManagerHeader.h"

@interface JCPlanIntelligentController ()<UITableViewDelegate,UITableViewDataSource,JCPickerViewDelegate,UITextFieldDelegate>

@property (nonatomic, strong) UITableView * intelligentTableView;

@property (nonatomic, strong) NSMutableArray * contentName;

@property (nonatomic, strong) NSMutableDictionary * dicTitle;

@property (nonatomic, strong) UIButton * billBtn;

@property (nonatomic, strong) UIView * footerView;

@property (nonatomic, strong) NSMutableArray * arrCity;

@property (nonatomic, strong) NSString * strType;// 类型
@property (nonatomic, strong) NSString * strProvince;// 省份
@property (nonatomic, strong) NSString * strCity;// 城市
@property (nonatomic, strong) NSString * benginDate;// 开始日期
@property (nonatomic, strong) NSString * endDate;// 结束日期
@property (nonatomic, strong) NSString * strQuota;// 额度
@property (nonatomic, strong) NSString * strAmount;// 总金额
@property (nonatomic, strong) NSString * strNumPens;// 总笔数


@property (nonatomic, strong) JCPickerView * dateView;//时间选择器

@end

@implementation JCPlanIntelligentController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"创建还款计划";

    [self DoRequsetArea];
    
    [self intelligentTableView];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.dicTitle[@"titleName"][section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {

        if (indexPath.row == 2 || indexPath.row == 3) {
            JCPlanTableViewCell * cell = [JCPlanTableViewCell tableViewCellWithTableView:tableView];
             [cell getPlanRepayment:self.dicTitle andSection:indexPath.section andIndexRow:indexPath.row];
            return cell;
        }else{
            JCPlanFieldCell * cell = [JCPlanFieldCell tableViewCellWithTableView:tableView];
            cell.contentField.tag = 200 + indexPath.row;
            cell.contentField.delegate = self;
             [cell getPlanRepayment:self.dicTitle andSection:indexPath.section andIndexRow:indexPath.row];
            return cell;
        }
    }else{
        JCPlanTableViewCell * cell = [JCPlanTableViewCell tableViewCellWithTableView:tableView];
            [cell getPlanRepayment:self.dicTitle andSection:indexPath.section andIndexRow:indexPath.row];
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return __I6Height(50);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 10;
    }else{
        return 40;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 40)];
    headerView.backgroundColor = [UIColor colorWithHexString:@"#F5F9FC"];
    UILabel * titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(__I6Width(15), 0, 200, 40)];
    [headerView addSubview:titleLabel];

    if (section == 1) {
        titleLabel.text = @"个人消费卡账户";
        titleLabel.textColor = [UIColor colorWithHexString:@"#009FFF"];
        titleLabel.font = KSHSystemFont(14);
    }else{
        titleLabel.text = nil;
    }
    
    return headerView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
//            [self getType];
        }else{
            [self getAddress];
        }
    }else{
        if (indexPath.row == 2 || indexPath.row == 3) {
            [self popDateView:indexPath.row];
        }
    }
}

- (UIView *)footerView{
    if (!_footerView) {
        _footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, __I6Height(90))];
        self.billBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.billBtn setTitle:@"制定账单" forState:UIControlStateNormal];
        self.billBtn.titleLabel.font = KSHSystemFont(14);
        [self.billBtn setTitleColor:[UIColor colorWithHexString:@"#FFFFFF"] forState:UIControlStateNormal];
        self.billBtn.layer.masksToBounds = YES;
        self.billBtn.layer.cornerRadius = 5;
        [self.billBtn addTarget:self action:@selector(billBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        [_footerView addSubview:self.billBtn];
        [self.billBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(_footerView);
            make.left.equalTo(_footerView).offset(__I6Width(15));
            make.right.equalTo(_footerView).offset(-__I6Width(15));
            make.height.mas_offset(__I6Height(40));
        }];
        [self.billBtn layoutIfNeeded];
        [self.billBtn.layer insertSublayer:[UIColor setGradualChangingColor:self.billBtn fromColor:@"#55B0F7" toColor:@"#0E8AEC"] atIndex:0];
    }
    
    return _footerView;
}

- (UITableView *)intelligentTableView{
    
    if (!_intelligentTableView) {
        _intelligentTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight - KNAVIGATIONBARHEIGHT) style:UITableViewStylePlain];
        _intelligentTableView.delegate = self;
        _intelligentTableView.dataSource = self;
        _intelligentTableView.backgroundColor = [UIColor colorWithHexString:@"#F5F9FC"];
        _intelligentTableView.tableFooterView = self.footerView;
        [self.view addSubview:_intelligentTableView];
    }
    return _intelligentTableView;
}

- (NSMutableArray *)contentName{
    if (!_contentName) {
        _contentName = [NSMutableArray arrayWithObjects:@[@"小额落地商户",@"",@""],@[@"请输入当前余额",@"请输入还款总金额",@"",@"",@"总笔数不得超过80笔"], nil];
    }
    return _contentName;
}

- (NSMutableDictionary *)dicTitle{
    if (!_dicTitle) {
        _dicTitle = [NSMutableDictionary dictionaryWithObjectsAndKeys:@[@[@"还款类别",@"落地商户所属省份",@"落地商户所属城市"],@[@"当前账户剩余额度",@"还款总金额",@"还款起始日期",@"还款终止日期"]],@"titleName",self
                     .contentName,@"contentName", nil];
    }
    
    return _dicTitle;
}

- (NSMutableArray *)arrCity{
    if (!_arrCity) {
        _arrCity = [NSMutableArray array];
    }
    return _arrCity;
}

//- (void)getType{
//    [self jxt_showActionSheetWithTitle:@"还款类别" message:nil appearanceProcess:^(JXTAlertController * _Nonnull alertMaker) {
//        alertMaker.
//        addActionCancelTitle(@"取消").
//        addActionDefaultTitle(@"小额落地商户").
//        addActionDestructiveTitle(@"大额还款");
//    } actionsBlock:^(NSInteger buttonIndex, UIAlertAction * _Nonnull action, JXTAlertController * _Nonnull alertSelf) {
//        if ([action.title isEqualToString:@"取消"]) {
//            NSLog(@"cancel");
//        }else{
//            self.strType = action.title;
//            NSMutableArray * arr = [self.contentName[0] mutableCopy];
//            [arr replaceObjectAtIndex:0 withObject:action.title];
//            [self.contentName replaceObjectAtIndex:0 withObject:arr];
//            [self.dicTitle setValue:self.contentName forKey:@"contentName"];
//            [self.intelligentTableView reloadData];
//        }
//    }];
//}

// 弹出省市
- (void)getAddress{
    if (self.arrCity.count > 0) {
        [JCAddressPickerView showWithDataArray:self.arrCity block:^(NSString *province, NSString *city) {
            self.strProvince = province;
            self.strCity = city;
            NSMutableArray * arr = [self.contentName[0] mutableCopy];
            [arr replaceObjectAtIndex:1 withObject:province];
            [arr replaceObjectAtIndex:2 withObject:city];
            [self.contentName replaceObjectAtIndex:0 withObject:arr];
            [self.dicTitle setValue:self.contentName forKey:@"contentName"];
            [self.intelligentTableView reloadData];
        }];
    }else{
        [self.view makeToast:@"正在维护" duration:2.f position:@"center"];
    }
    
}

// 弹出时间选择器
- (void)popDateView:(NSInteger)tag{
    self.dateView= [[JCPickerView alloc] initDatePickerWithDefaultDate:nil andDatePickerMode:UIDatePickerModeDate];
    self.dateView.dateTag = tag;
    self.dateView.datePicker.minimumDate = [NSDate date];
    self.dateView.delegate = self;
    [self.dateView show];
}

#pragma mark -- 时间选择器delegate
- (void)pickerView:(JCPickerView *)pickerView didSelectDateString:(NSString *)dateString{

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    if (self.dateView.dateTag == 2) {
        //比较时间
        int result =  [Tool compareOneDay:[dateFormatter dateFromString:dateString] withAnotherDay:[dateFormatter dateFromString:self.endDate]];

        if (result == 1) {
            [Tool alertWithMessage:@"起始时间大于结束时间" who:self];
            return;
        }
        self.benginDate = dateString;
    }else{
        
        int result =  [Tool compareOneDay:[dateFormatter dateFromString:dateString] withAnotherDay:[dateFormatter dateFromString:self.benginDate]];
        if (result == -1) {
            [Tool alertWithMessage:@"结束时间小于起始时间" who:self];
            return;
        }
        self.endDate = dateString;
    }
    
    NSMutableArray * arr = [self.contentName[1] mutableCopy];
    [arr replaceObjectAtIndex:self.dateView.dateTag withObject:dateString];
    [self.contentName replaceObjectAtIndex:1 withObject:arr];
    [self.dicTitle setValue:self.contentName forKey:@"contentName"];
    [self.intelligentTableView reloadData];
}

#pragma mark - UITextDelegate
- (void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField.tag == 200) {
        if ([textField.text floatValue] < 500) {
            [self.view makeToast:@"当前账户剩余额度不低于500元" duration:2.f position:@"center"];
            textField.text = @"";
        }else{
            self.strQuota = textField.text;
        }
    }else {
        if ([textField.text floatValue] < 600) {
            [self.view makeToast:@"还款总金额不低于600元" duration:2.f position:@"center"];
            textField.text = nil;
        }else{
            self.strAmount = textField.text;
        }
    }
//    else {
//        if ([textField.text integerValue] > 80) {
//            [Tool alertWithMessage:@"总笔数不得超过80" who:self];
//            textField.text = nil;
//        }else if ([textField.text integerValue] == 0){
//            [Tool alertWithMessage:@"最少一笔" who:self];
//            textField.text = nil;
//        }else{
//            self.strNumPens = textField.text;
//        }
//    }
}

// 点击制定账单
- (void)billBtnAction:(UIButton *)btn{
    
    if (self.strProvince == nil || self.strCity == nil) {
        [self.view makeToast:@"请选择省份和城市" duration:2.f position:@"center"];
    }else if (self.strQuota == nil){
        [self.view makeToast:@"请输入当前账户剩余额度" duration:2.f position:@"center"];
    }else if (self.strAmount == nil){
        [self.view makeToast:@"请输入还款总金额" duration:2.f position:@"center"];
    }else if (self.benginDate == nil){
        [self.view makeToast:@"请选择还款起始日期" duration:2.f position:@"center"];
    }else if (self.endDate == nil){
        [self.view makeToast:@"请选择还款终止日期" duration:2.f position:@"center"];
    }
//    else if (self.strNumPens == nil){
//        [self.view makeToast:@"请输入还款笔数" duration:2.f position:@"center"];
//    }
    else{
        [self DoRequsetR_plan_preview];
    }
}

#pragma mark - 网络请求
// 获取落地支持区域
- (void)DoRequsetArea{
    
    [PPNetworkHelper GET:H_down_area parameters:@{@"cooperator_user_id":self.model.cooperator_user_id} cache:NO encrypt:NO decode:NO responseCache:^(id responseCache) {
        
    } success:^(id result) {
        
        if ([result[@"success"] boolValue] == 1) {
            NSDictionary * dic = [NSDictionary dictionaryWithDictionary:result[@"data"]];
            NSMutableArray * arrPC = [NSMutableArray array];
            for (NSDictionary * dicPro in dic[@"provinceList"]) {
                NSMutableDictionary * dict = [NSMutableDictionary dictionary];
                NSMutableArray * cityArr = [NSMutableArray array];
                
                for (NSDictionary * dicCity in dic[@"cityList"]) {
                    if ([dicPro[@"id"] isEqualToString:dicCity[@"parentId"]]) {
                        [cityArr addObject:dicCity];
                    }
                    [dict setObject:cityArr forKey:@"cities"];
                    [dict setObject:dicPro[@"value"] forKey:@"name"];
                }
                
                [arrPC addObject:dict];
            }
            
            NSMutableArray *nmArray = [NSMutableArray arrayWithCapacity:arrPC.count];
            for (NSDictionary *dic in arrPC) {
                [nmArray addObject:[city citiesWithDic:dic]];
            }
            [self.arrCity removeAllObjects];
            [self.arrCity addObjectsFromArray:nmArray];
            
        }else{
            [self.view makeToast:result[@"data"] duration:2.f position:@"center"];
        }
        
    } failure:^(NSError *error) {
        
    }];
    
}

// 制定职能账单
- (void)DoRequsetR_plan_preview{
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dic setValue:self.model.cardNo forKey:@"cardNo"];
    [dic setValue:@"1" forKey:@"channel_type"];
    [dic setValue:self.strQuota forKey:@"balance"];
    [dic setValue:self.strAmount forKey:@"amount"];
    [dic setValue:[NSString stringWithFormat:@"%@,%@",self.benginDate,self.endDate] forKey:@"days"];
    
    JCBillPreviewController * billVC = [[JCBillPreviewController alloc] init];
    billVC.strAmount = self.strAmount;
    billVC.strNumPens = self.strNumPens;
    billVC.dicData = dic;
    billVC.strCity = self.strCity;
    billVC.strProvince = self.strProvince;
    [self.navigationController pushViewController:billVC animated:YES];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
